package com.quanyan.common.http;


import com.squareup.okhttp.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.Map.Entry;

/**
 * Https/http get. post请求工具类.
 * Created by zijun.song on 2015/6/30.
 */
public class  HttpClientUtils {

    private static HttpClient client = null;

    static {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        cm.setMaxTotal(128);
        cm.setDefaultMaxPerRoute(128);
        client = HttpClients.custom().setConnectionManager(cm).build();
    }

    /**
     * @param url
     * @param body a=1&b=2
     * @return
     * @throws Exception
     */
    public static String post(String url, String body) throws Exception {
        HttpPost post = new HttpPost(url);
        if (StringUtils.isNotBlank(body)) {
            HttpEntity entity = new StringEntity(body, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return post(post, 5000, 3000);
    }


    /**
     * @param url
     * @param json
     * @return
     * @throws Exception
     */
    public static String postJson(String url, String json) throws Exception {
        HttpPost post = new HttpPost(url);
        if (StringUtils.isNotBlank(json)) {
            post.addHeader("Content-Type", "application/json");
            HttpEntity entity = new StringEntity(json, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return post(post, 5000, 3000);
    }

    /**
     * 设置超时时间
     * @param url
     * @param json
     * @param connTimeout
     * @param readTimeout
     * @return
     * @throws Exception
     */
    public static String postJson(String url, String json,Integer connTimeout, Integer readTimeout) throws Exception {
        HttpPost post = new HttpPost(url);
        if (StringUtils.isNotBlank(json)) {
            post.addHeader("Content-Type", "application/json");
            HttpEntity entity = new StringEntity(json, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return post(post, connTimeout, readTimeout);
    }

    /**
     * 请求添加头
     * @param url
     * @param json
     * @param headerMap
     * @return
     * @throws Exception
     */
    public static String postJson(String url, String json,Map<String,String> headerMap) throws Exception {
        HttpPost post = new HttpPost(url);
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if (StringUtils.isNotBlank(json)) {
            post.addHeader("Content-Type", "application/json");
            HttpEntity entity = new StringEntity(json, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return post(post, 5000, 3000);
    }

    /**
     * 请求添加头
     * @param url
     * @param body
     * @param headerMap
     * @return
     * @throws Exception
     */
    public static String postXml(String url, String body,Map<String,String> headerMap) throws Exception {
        HttpPost post = new HttpPost(url);
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if (StringUtils.isNotBlank(body)) {
            post.addHeader("Content-Type", "text/xml");
            HttpEntity entity = new StringEntity(body, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return post(post, 5000, 3000);
    }

    /**
     * @param url
     * @param body
     * @return
     * @throws Exception
     */
    public static String postXml(String url, String body) throws Exception {
        HttpPost post = new HttpPost(url);
        if (StringUtils.isNotBlank(body)) {
            post.addHeader("Content-Type", "text/xml");
            HttpEntity entity = new StringEntity(body, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return post(post, 5000, 3000);
    }

    /**
     * @param url
     * @param paramMap
     * @return
     * @throws Exception
     */
    public static String post(String url, Map<String, String> paramMap) throws Exception {
        HttpPost post = new HttpPost(url);
        if (paramMap != null && paramMap.size() > 0) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            Iterator<Entry<String, String>> iterator = paramMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> key = iterator.next();
                params.add(new BasicNameValuePair(key.getKey(), key.getValue()));
            }
            post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));

        }
        return post(post, 5000, 3000);
    }

    /**
     * 发送一个 Post 请求, 使用指定的字符集编码.
     *
     * @param post
     * @param connTimeout 建立链接超时时间,毫秒.
     * @param readTimeout 响应超时时间,毫秒.
     * @return ResponseBody, 使用指定的字符集编码.
     * @throws ConnectTimeoutException 建立链接超时异常
     * @throws SocketTimeoutException  响应超时
     * @throws Exception
     */
    private static String post(HttpPost post, Integer connTimeout, Integer readTimeout)
            throws Exception {
        HttpClient client = null;
        String result = "";
        try {

            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());

            HttpResponse res;
            if (post.getURI().toString().startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            result = IOUtils.toString(res.getEntity().getContent(), Consts.UTF_8.toString());
        } finally {
            post.releaseConnection();
            if (post.getURI().toString().startsWith("https") && client != null
                    && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 提交form表单
     *
     * @param url
     * @param params
     * @param connTimeout
     * @param readTimeout
     * @return
     * @throws ConnectTimeoutException
     * @throws SocketTimeoutException
     * @throws Exception
     */
    public static String postForm(String url, Map<String, String> params,
                                  Map<String, String> headers, Integer connTimeout,
                                  Integer readTimeout) throws
            Exception {

        HttpClient client = null;

        HttpPost post = new HttpPost(url);
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> formParams = new ArrayList<NameValuePair>();
                Set<Entry<String, String>> entrySet = params.entrySet();
                for (Entry<String, String> entry : entrySet) {
                    formParams.add(new BasicNameValuePair(entry.getKey(), entry
                            .getValue()));
                }
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
                        formParams, Consts.UTF_8);
                post.setEntity(entity);
            }
            if (headers != null && !headers.isEmpty()) {
                for (Entry<String, String> entry : headers.entrySet()) {
                    post.addHeader(entry.getKey(), entry.getValue());
                }
            }
            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());
            HttpResponse res = null;
            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            return IOUtils.toString(res.getEntity().getContent(), Consts.UTF_8.toString());
        } finally {
            post.releaseConnection();
            if (url.startsWith("https") && client != null
                    && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
    }

    /**
     * 发送一个 GET 请求
     *
     * @param url
     * @param charset
     * @return
     * @throws Exception
     */
    public static String get(String url, String charset) throws Exception {
        return get(url, charset, null, null);
    }

    /**
     * 默认为UTF-8的Get请求
     *
     * @param url
     * @return
     * @throws Exception
     */
    public static String get(String url) throws Exception {
        return get(url, Consts.UTF_8.toString());
    }

    /**
     * 发送一个 GET 请求
     *
     * @param url
     * @param charset
     * @param connTimeout 建立链接超时时间,毫秒.
     * @param readTimeout 响应超时时间,毫秒.
     * @return
     * @throws ConnectTimeoutException 建立链接超时
     * @throws SocketTimeoutException  响应超时
     * @throws Exception
     */
    public static String get(String url, String charset, Integer connTimeout,
                             Integer readTimeout) throws
            Exception {
        HttpClient client = null;

        HttpGet get = new HttpGet(url);
        String result = "";
        try {
            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            get.setConfig(customReqConf.build());

            HttpResponse res = null;

            if (url.startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(get);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(get);
            }

            result = IOUtils.toString(res.getEntity().getContent(), charset);
        } finally {
            get.releaseConnection();
            if (url.startsWith("https") && client != null
                    && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return result;
    }

    /**
     * 从 response 里获取 charset
     *
     * @param ressponse
     * @return
     */
    @SuppressWarnings("unused")
    private static String getCharsetFromResponse(HttpResponse ressponse) {
        // Content-Type:text/html; charset=GBK
        if (ressponse.getEntity() != null
                && ressponse.getEntity().getContentType() != null
                && ressponse.getEntity().getContentType().getValue() != null) {
            String contentType = ressponse.getEntity().getContentType()
                    .getValue();
            if (contentType.contains("charset=")) {
                return contentType
                        .substring(contentType.indexOf("charset=") + 8);
            }
        }
        return null;
    }

    private static CloseableHttpClient createSSLInsecureClient()
            throws GeneralSecurityException {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(
                    null, new TrustStrategy() {
                        public boolean isTrusted(X509Certificate[] chain,
                                                 String authType) throws CertificateException {
                            return true;
                        }
                    }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslContext, new X509HostnameVerifier() {

                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                public void verify(String host, SSLSocket ssl)
                        throws IOException {
                }

                public void verify(String host, X509Certificate cert)
                        throws SSLException {
                }

                public void verify(String host, String[] cns,
                                   String[] subjectAlts) throws SSLException {
                }

            });
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (GeneralSecurityException e) {
            throw e;
        }
    }


    private static Map postResponse(HttpPost post, Integer connTimeout, Integer readTimeout)
            throws Exception {
        HttpClient client = null;
        Map map = new HashMap();
        String result = "";
        try {

            // 设置参数
            RequestConfig.Builder customReqConf = RequestConfig.custom();
            if (connTimeout != null) {
                customReqConf.setConnectTimeout(connTimeout);
            }
            if (readTimeout != null) {
                customReqConf.setSocketTimeout(readTimeout);
            }
            post.setConfig(customReqConf.build());

            HttpResponse res;
            if (post.getURI().toString().startsWith("https")) {
                // 执行 Https 请求.
                client = createSSLInsecureClient();
                res = client.execute(post);
            } else {
                // 执行 Http 请求.
                client = HttpClientUtils.client;
                res = client.execute(post);
            }
            result = IOUtils.toString(res.getEntity().getContent(), Consts.UTF_8.toString());
            map.put("result",result);
            map.put("status",res.getStatusLine().getStatusCode());
        } finally {
            post.releaseConnection();
            if (post.getURI().toString().startsWith("https") && client != null
                    && client instanceof CloseableHttpClient) {
                ((CloseableHttpClient) client).close();
            }
        }
        return map;
    }

    public static Map postJsonResponse(String url, String json,Map<String,String> headerMap) throws Exception {
        HttpPost post = new HttpPost(url);
        if (headerMap != null && headerMap.size() > 0) {
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }
        if (StringUtils.isNotBlank(json)) {
            post.addHeader("Content-Type", "application/json");
            HttpEntity entity = new StringEntity(json, ContentType.create(
                    "application/x-www-form-urlencoded", Consts.UTF_8));
            post.setEntity(entity);
        }
        return postResponse(post, 5000, 3000);
    }

    /**
     * post 返回字节
     * @param url
     * @param json
     * @return
     */
    public static byte[] sendPost(String url,String json){
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        OkHttpClient client = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().bytes();
            } else {
                throw new IOException("Unexpected code " + response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }


}
